﻿using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc;
using KongMing.Project.Common;
using KongMing.Project.Entity.Common;

namespace KongMing.Project.WebApi.Filters
{
    public class GlobalApiResultFilter: IResultFilter
    {
        public void OnResultExecuted(ResultExecutedContext context)
        {
        }

        public void OnResultExecuting(ResultExecutingContext context)
        {
            if (!(context.Controller is BaseMVCController || context.Controller is BaseApiController))
                return;
            if (context.Controller is BaseMVCController && context.Result is ViewResult)
                return;
            if (context.Result is EmptyResult _e)
            {
                context.Result = new ObjectResult(BaseApiResult.Success());
            }
            if(context.Result is ObjectResult _o)
            {
                if (_o.Value is BaseApiResult) { }
                else
                    context.Result = new ObjectResult(BaseApiResult.Success(_o.Value));
            }
            var objectresult = context.Result as ObjectResult;
            var cotentresult = new ContentResult()
            {
                Content =  Tools.ToJson(objectresult.Value),
                ContentType = "application/json",
                StatusCode = 200
            };
            context.Result = cotentresult;
        }
    }
}
